# ElementTree表示整个XML节点树而Element表示节点数中的一个单独的节点
import xml.etree.ElementTree as ET
# 增
new_xml = ET.Element("namelist")  # 设置一个根节点，标签为namelist
# 设置new_xml节点的子节点
name = ET.SubElement(new_xml, "name", attrib={"enrolled": "yes"})
age = ET.SubElement(name, "age", attrib={"checked": "no"})
age.text = '33'
sex = ET.SubElement(name, "sex")  # 标签名
sex.text = '33'  # 设置标签值
# attrib:属性
name2 = ET.SubElement(new_xml, "name", attrib={"enrolled": "no"})
age01 = ET.SubElement(name2, "age")
age01.text = '19'
et = ET.ElementTree(new_xml)  # 生成文档对象
# 写入文件
et.write("test.xml", encoding="utf-8", xml_declaration=True)
ET.dump(new_xml)  # 打印生成的xml
# 删除,修改
tree = ET.parse("test.xml")  # 加载xml文件并返回ElementTree对象
root = tree.getroot()  # 获取根节点
# 修改
# iter: 返回一个匹配的iterator
for node in root.iter("name"):  # 获取root下所有name标签
    for age in node.iter("age"):  # 获取所有age标签
        age.text = '44'  # 修改
# 删除
# findall: 返回匹配的所有标签列表
# find: 返回匹配的第一个标签
for name in root.findall('name'):
    for sex in name.findall('sex'):
        name.remove(sex)  # 删除sex节点
# 将修改删除保存持久化到文件中
tree.write('test.xml')